package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.cloud.gateway.handler.predicate.MethodRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
class PidAndNumRoutePredicateFactory extends AbstractRoutePredicateFactory<PidAndNumRoutePredicateFactory.config> {

    public PidAndNumRoutePredicateFactory(){
        super(config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid","maxPid","minNum","maxNum");
    }

    @Override
    public Predicate<ServerWebExchange> apply(config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();
                String[] split=path.split("/");
                String pidString = split[split.length - 2];
                String numString = split[split.length-1];
                int pid=Integer.parseInt(pidString);
                int num=Integer.parseInt(numString);
                if (config.getMinPid()<=pid&&pid<=config.getMaxPid()||config.getMinNum()<=num&&num<=config.getMaxPid()){
                    return true;
                }else {
                    return false;
                }
            }
        };
    }


    public static class config{
        private int minPid;
        private int maxPid;
        private int minNum;
        private int maxNum;

        public int getMinPid() {
            return minPid;
        }

        public void setMinPid(int minPid) {
            this.minPid = minPid;
        }

        public int getMaxPid() {
            return maxPid;
        }

        public void setMaxPid(int maxPid) {
            this.maxPid = maxPid;
        }

        public int getMinNum() {
            return minNum;
        }

        public void setMinNum(int minNum) {
            this.minNum = minNum;
        }

        public int getMaxNum() {
            return maxNum;
        }

        public void setMaxNum(int maxNum) {
            this.maxNum = maxNum;
        }
    }
}
